package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tycmc.functions.util.MapGetter;

import net.tycmc.bulb.common.dao.IBaseDAO;
import net.tycmc.bulb.common.dao.ITransactionDAO;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.cty.ctyms.timejob.common.DateRegUtil;

public class VclStateStatConn {
	
	private IBaseDAO baseDAO;
	
	private ITransactionDAO tranDAO;

	public IBaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public ITransactionDAO getTranDAO() {
		return tranDAO;
	}

	public void setTranDAO(ITransactionDAO tranDAO) {
		this.tranDAO = tranDAO;
	}
	//开始统计
	public void startStat(){
		//获得昨天的日期字符串，格式yyyyMMdd
		String tableDate = DateUtil.addDay(-1).replace("-", "");
		//需统计设备
		List<Map<String,Object>> list = this.getVclInfo(tableDate);
		if(list!=null){
			int size = list.size();
			for(int i = 0;i<size;i++){
				Map<String,Object> map = list.get(i);
				if(map.get("VehicleID")==null)continue;
				List<Map<String,Object>> list_stat = this.getRimaryData(tableDate, map.get("VehicleID").toString());
				forEachData(list_stat);
			}
			//根据统计的设备状态统计开机时长
			statKeyOnTime();
		}
	}
	
	/**
	 * 统计计算开机时长
	 */
	public void statKeyOnTime(){
		//获得昨天的日期字符串，格式yyyyMMdd
		String tableDate = DateUtil.addDay(-1);
		String queryBgDa = tableDate+" 00:00:00";
		String queryEdDa = tableDate+" 23:59:59";
		StringBuffer sb = new StringBuffer();
		sb.append(" insert into Message_Stat_VclKeyOn (Msvk_VclID,Msvk_StatTime,Msvk_KeyOnTime)");
		sb.append(" select MsgSVS_VclID,Convert(NVARCHAR(10),MsgSVS_BgnTime,120) ms,ISNULL(SUM (DATEDIFF(S,MsgSVS_BgnTime,MsgSVS_EndTime)),0) keyOnTime ");
		sb.append(" from Message_Stat_VclState left join V_VehicleInfo on MsgSVS_VclID = VehicleID");
		sb.append(" where MsgSVS_BgnTime>='"+queryBgDa+"' and MsgSVS_EndTime<= '"+queryEdDa+"' ");
		sb.append(" and (MsgSVS_State = '1' or MsgSVS_State = '3') group by MsgSVS_VclID,Convert(NVARCHAR(10),MsgSVS_BgnTime,120) ");
		try{
			int i = baseDAO.execInsert(sb.toString(), new Object[]{});
			if(i>0){
				System.out.println("统计计算开机时长,插入表-------------------成功！");
			} else{
				System.out.println("统计计算开机时长,插入表-------------------失败！");
			}
		}catch(Exception e){
			System.out.println("统计计算开机时长,插入表-------------------失败,异常："+e);
		}
	}
	/**
	 * 获得原始数据
	 */
	public List<Map<String,Object>> getRimaryData(String tableDate,String vclID){
		//表是否存在
		//大一
		String isExt_Big = "select count(1) as cnt from CTY_Egn_A.dbo.SysObjects Where XType='U' and Name=?";
		Map<String,Object> isExtMap_Big = baseDAO.execQueryOne(isExt_Big, new Object[]{"Msg_Timing_Pstn_"+tableDate});
		//小一
		//软件版本号3.4
		String isExt_Small_3_4 = "select count(1) as cnt from CTY_Egn_B.dbo.SysObjects Where XType='U' and Name=?";
		Map<String,Object> isExtMap_Small_3_4 = baseDAO.execQueryOne(isExt_Small_3_4, new Object[]{"Msg_Timing_"+tableDate});
		
		//统计设备状态信息
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("select vvi.VehicleID,MessageTime,KeyStatus,EngineStatus from V_VehicleInfo as vvi inner join (");
		//大一
		if("1".equals(isExtMap_Big.get("cnt").toString())){
			strBuff.append("select MsgTPs_Vcl_ID VehicleID,MsgTPs_MsgTime MessageTime,MsgTPs_Switch KeyStatus,EngineStatus=case when MsgTPs_Engine='true' then '1' else '0' end from CTY_Egn_A.dbo.Msg_Timing_Pstn_"+tableDate+" where MsgTPs_Vcl_ID="+vclID+" ");
		}
		//小一
		//软件版本号3.4
		if("1".equals(isExtMap_Small_3_4.get("cnt").toString())){
			if("1".equals(isExtMap_Big.get("cnt").toString()))strBuff.append("union ");
			strBuff.append("select MsgT_Vcl_ID VehicleID,MsgT_MsgTime MessageTime,MsgT_KeyState KeyStatus,MsgT_EgnState EngineStatus from CTY_Egn_B.dbo.Msg_Timing_"+tableDate+" where MsgT_Vcl_ID="+vclID+"");
		}
		
		if(!"1".equals(isExtMap_Big.get("cnt").toString())&&!"1".equals(isExtMap_Small_3_4.get("cnt").toString())){
			return null;
		}else{
			strBuff.append(") as tmp on tmp.VehicleID=vvi.VehicleID order by MessageTime");
		}
		return baseDAO.execQuery(strBuff.toString(), new Object[]{});
	}
	/**
	 * 遍历原始数据，数据的逻辑判断
	 */
	public void forEachData(List<Map<String,Object>> list){
		Map<String,Object>map=new HashMap<String,Object>();
		
		/*if(list==null)return ;*/
		//临时MAP，用来存放设备的当前状态
		Map<String,Object> tmpMap = new HashMap<String,Object>();
		int size = list.size();
		for(int i = 0;i<size;i++){
			if(list.get(i).get("VehicleID")==null)continue;
			//设备ID
			String vclID = list.get(i).get("VehicleID").toString();
			//信息时间
			String msgTime = list.get(i).get("MessageTime")!=null?list.get(i).get("MessageTime").toString():"";
			//如果数据信息时间不是昨天，则过滤掉
			if(msgTime.indexOf(DateUtil.addDay(-1))<0)continue;
			//KEY状态
			int keyState = Integer.valueOf(list.get(i).get("KeyStatus")!=null?list.get(i).get("KeyStatus").toString():"0");
			//ENG状态
			int engState = Integer.valueOf(list.get(i).get("EngineStatus")!=null?list.get(i).get("EngineStatus").toString():"0");
			//整合后状态
			int conState = convertState(keyState, engState);
			
			//初始化状态
			if(tmpMap.isEmpty()){
				tmpMap.put("vclID", vclID);
				//判断第一条数据是否是00:00:00，如果不是则初始化00:00:00:的状态为KEY OFF。
				if(msgTime.indexOf("00:00:00")<0){
					tmpMap.put("conState", 2);
					tmpMap.put("msgTime", msgTime.substring(0, 11)+" 00:00:00");
				}else{
					tmpMap.put("conState", conState);
					tmpMap.put("msgTime", msgTime);
				}
			}
			
			int conStateTmp = Integer.valueOf(tmpMap.get("conState").toString());
			
			//判断遍历项是否是最后一条数据
			if(i+1==size){
				//判断遍历项状态与前一条状态是否一致
				if(conState==conStateTmp){
					istStatData(vclID, tmpMap.get("msgTime").toString(), msgTime.substring(0, 11)+" 23:59:59", conStateTmp);
				}else{
					istStatData(vclID, tmpMap.get("msgTime").toString(), msgTime, conStateTmp);
					if(msgTime.indexOf("23:59:59")<0){
					}
					this.istStatData(vclID, msgTime, msgTime.substring(0, 11)+" 23:59:59", conState);
				}
			}else{
				//判断遍历项状态与前一条状态是否一致
				if(conState!=Integer.valueOf(tmpMap.get("conState").toString())){
					istStatData(vclID, tmpMap.get("msgTime").toString(), msgTime, conStateTmp);
					tmpMap.put("conState", conState);
					tmpMap.put("msgTime", msgTime);
				}
			}
		}
	}
	
	/**
	 * 向统计表插入数据
	 * @param vclID
	 * @param bgnTime
	 * @param endTime
	 * @param state
	 * @return
	 */
	public boolean istStatData(String vclID,String bgnTime,String endTime,int state){
		List<Map<String,Object>> list_stats = this.getRimaryLOLA(bgnTime, endTime,vclID);
		String beginlo=null;
		String beginla=null;
		String endlo=null;
		String endla=null;
		if(list_stats!=null&&list_stats.size()>0){
			beginlo=MapGetter.getString(list_stats.get(0),"vclp_lo");
			beginla=MapGetter.getString(list_stats.get(0),"vclp_la");
			endlo=MapGetter.getString(list_stats.get(1),"vclp_lo");
			endla=MapGetter.getString(list_stats.get(1),"vclp_la");
		}
		String strSQL = "insert into Message_Stat_VclState (MsgSVS_VclID,MsgSVS_BgnTime,MsgSVS_EndTime,MsgSVS_State,MsgSVS_Blo,MsgSVS_BLa,MsgSVS_ELo,MsgSVS_Ela,MsgSVS_CndRunSec) values(?,?,?,?,?,?,?,?,datediff(s,'"+bgnTime+"','"+endTime+"'));";
		int i = baseDAO.execInsert(strSQL, new Object[]{vclID,bgnTime,endTime,state,beginlo,beginla,endlo,endla});
		if(i>0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 状态转换   1：KEY ON&ENG OFF  2：KEY OFF  3： ENG ON
	 */
	public int convertState(int keyState,int engState){
		int state = 1;
		if(keyState==1&&engState==0){
			state = 1;
		}else if(keyState==0){
			state = 2;
		}else{
			state = 3;
		}
		return state;
	}
	
	/**
	 * 获取需要统计的有效设备
	 * @param tableDate
	 * @return
	 */
	public List<Map<String,Object>> getVclInfo(String tableDate){
		boolean isExt_Big = isExtTab("CTY_Egn_A","Msg_Timing_Pstn_"+tableDate);
		boolean isExt_Small = isExtTab("CTY_Egn_B","Msg_Timing_"+tableDate);
		
		String strSQL = "select distinct vi.VehicleID,vi.VehicleNumber from V_VehicleInfo as vi inner join (";
		
		if(isExt_Big)strSQL += "select MsgTPs_Vcl_ID VehicleID from CTY_Egn_A.dbo.Msg_Timing_Pstn_"+tableDate+"";
		if(isExt_Small){
			if(isExt_Big)strSQL += " union ";
			strSQL += "select MsgT_Vcl_ID VehicleID from CTY_Egn_B.dbo.Msg_Timing_"+tableDate+"";
		}
		strSQL += " ) as stateTable on stateTable.VehicleID=vi.VehicleID where UsefulLife>=GETDATE()";
		if(isExt_Big||isExt_Small){
			return baseDAO.execQuery(strSQL, new Object[]{});
		}else{
			return null;
		}
	}
	/**
	 * 判断表是否存在
	 * @param tabName
	 * @return
	 */
	public boolean isExtTab(String dataName,String tabName){
		String isExt = "select count(1) as cnt from "+dataName+".dbo.SysObjects Where XType='U' and Name=?";
		Map<String,Object> isExtMap = baseDAO.execQueryOne(isExt, new Object[]{tabName});
		if(isExtMap.get("cnt")!=null&&"1".equals(isExtMap.get("cnt").toString()))return true;
		return false;
	}
	/**
	 * 多天位置表关联，获取经纬度
	 * @param tabName
	 * @return
	 */
	public List<Map<String,Object>> getRimaryLOLA(String beginTime,String endTime,String vclId){
		List<String> list=DateRegUtil.iterateTime(beginTime,endTime);
		String sql="";
		for(String time:list){
			time=time.replaceAll("-","");
			 sql+="select vclp_vcl_id,vclp_pstntime,vclp_lo,vclp_la from cty_vcl.dbo.vcl_pstn_"+time+" where vclp_pstntime>='"+beginTime+"' and vclp_pstntime<='"+endTime+"' and vclp_vcl_id="+vclId+" and vclp_lo is not null and vclp_lo!=0 and vclp_la is not null and vclp_la!=0 union all ";
		}
		if(sql.length()>10){
			sql=sql.substring(0,sql.length()-10);
		}

		String sqlResult=" select * from (select top 1 * from ("+sql+")aa  order by vclp_pstntime asc)cc ";
		sqlResult+=" union all select * from ( select top 1 * from ("+sql+")aa  order by vclp_pstntime desc)cc ";
		System.out.println(sqlResult);
	return baseDAO.execQuery(sqlResult,new Object[]{});
		
	}
}
